﻿using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace AnyExeTo.WindowsService
{
    /// <summary>
    /// 程序
    /// </summary>
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                var options = ServiceOptions.LoadFromFile();
                var servicesToRun = new ServiceBase[1];
                if (string.IsNullOrWhiteSpace(options.ServiceName))
                {
                    servicesToRun[0] = new AnyExeToService();
                }
                else
                {
                    servicesToRun[0] = new AnyExeToService { ServiceName = options.ServiceName };
                }
                ServiceBase.Run(servicesToRun);
            }
            else if (Array.Exists(args, r => r == "install"))
            {
                var commandLine = new[] { Assembly.GetExecutingAssembly().Location };
                ManagedInstallerClass.InstallHelper(commandLine);
            }
            else if (Array.Exists(args, r => r == "uninstall"))
            {
                var commandLine = new[] { "-uninstall", Assembly.GetExecutingAssembly().Location };
                ManagedInstallerClass.InstallHelper(commandLine);
            }
            else if (Array.Exists(args, r => r == "/?" || r == "help"))
            {
                MessageBox.Show(Properties.Resources.Help, @"帮助", MessageBoxButtons.OK, MessageBoxIcon.Question);
            }
            else if (Array.Exists(args, r => r == "options"))
            {
                var staThreadForForm = new Thread(() =>
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new FormServiceOptions());
                });
                staThreadForForm.SetApartmentState(ApartmentState.STA);
                staThreadForForm.Start();
                staThreadForForm.Join();
            }
            else if (Array.Exists(args, r => r == "ren"))
            {
                var index = Array.FindIndex(args, r => r == "ren");
                if (index + 1 < args.Length)
                {
                    var newName = args[index + 1];
                    var fileName = Assembly.GetExecutingAssembly().Location;
                    var directory = Path.GetDirectoryName(fileName);
                    var newFileName = Path.Combine(directory, $"{newName}.exe");
                    if (!File.Exists(newFileName))
                    {
                        File.Move(fileName, Path.Combine(directory, $"{newName}.exe"));

                        var configFile = Path.ChangeExtension(fileName, ".exe.config");
                        if (File.Exists(configFile))
                        {
                            File.Move(configFile, Path.Combine(directory, $"{newName}.exe.config"));
                        }

                        var jsonFile = Path.ChangeExtension(fileName, ".json");
                        if (File.Exists(jsonFile))
                        {
                            File.Move(jsonFile, Path.Combine(directory, $"{newName}.json"));
                        }

                        var pdbFile = Path.ChangeExtension(fileName, ".pdb");
                        if (File.Exists(pdbFile))
                        {
                            File.Move(pdbFile, Path.Combine(directory, $"{newName}.pdb"));
                        }
                    }
                }
            }
            else if (Array.Exists(args, r => r == "status"))
            {
                var options = ServiceOptions.LoadFromFile();
                if (!string.IsNullOrWhiteSpace(options.ServiceName))
                {
                    var serviceController = new ServiceController(options.ServiceName);
                    try
                    {
                        MessageBox.Show(serviceController.Status.ToString("G"), @"服务状态", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (InvalidOperationException)
                    {
                        MessageBox.Show(@"服务不存在！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else if (Array.Exists(args, r => r == "start"))
            {
                var options = ServiceOptions.LoadFromFile();
                if (!string.IsNullOrWhiteSpace(options.ServiceName))
                {
                    var serviceController = new ServiceController(options.ServiceName);
                    try
                    {
                        if (serviceController.Status == ServiceControllerStatus.Stopped)
                        {
                            serviceController.Start();
                            try
                            {
                                serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
                            }
                            catch (System.ServiceProcess.TimeoutException)
                            {
                                // 忽略
                            }
                            if (serviceController.Status != ServiceControllerStatus.Running)
                            {
                                MessageBox.Show(serviceController.Status.ToString("G"), @"服务状态", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        MessageBox.Show(@"服务不存在！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else if (Array.Exists(args, r => r == "stop"))
            {
                var options = ServiceOptions.LoadFromFile();
                if (!string.IsNullOrWhiteSpace(options.ServiceName))
                {
                    var serviceController = new ServiceController(options.ServiceName);
                    try
                    {
                        if (serviceController.Status == ServiceControllerStatus.Running)
                        {
                            serviceController.Stop();
                            try
                            {
                                serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
                            }
                            catch (System.ServiceProcess.TimeoutException)
                            {
                                // 忽略
                            }
                            if (serviceController.Status != ServiceControllerStatus.Stopped)
                            {
                                MessageBox.Show(serviceController.Status.ToString("G"), @"服务状态", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        MessageBox.Show(@"服务不存在！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else if (Array.Exists(args, r => r == "exists"))
            {
                var options = ServiceOptions.LoadFromFile();
                if (!string.IsNullOrWhiteSpace(options.ServiceName))
                {
                    var serviceControllers = ServiceController.GetServices();
                    if (Array.Exists(serviceControllers, r => r.ServiceName == options.ServiceName))
                    {
                        MessageBox.Show($@"指定服务存在。{options.ServiceName}", @"服务状态", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show($@"指定服务不存在。{options.ServiceName}", @"服务状态", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            else
            {
                MessageBox.Show(Properties.Resources.Help, @"帮助", MessageBoxButtons.OK, MessageBoxIcon.Question);
            }
        }
    }
}
